package com.alifi.crm.web.home.action;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;

import net.sf.json.JSONObject;

import com.alibaba.buc.sso.client.util.SimpleUserUtil;
import com.alibaba.citrus.turbine.Context;
import com.alibaba.citrus.turbine.Navigator;
import com.alibaba.common.lang.StringUtil;
import com.alibaba.common.logging.Logger;
import com.alibaba.common.logging.LoggerFactory;
import com.alibaba.platform.buc.sso.common.dto.SimpleSSOUser;
import com.alifi.crm.biz.guess.GuessMessage;
import com.alifi.crm.biz.lottery.LotteryManager;
import com.alifi.crm.biz.lottery.LotteryResult;
import com.alifi.crm.dal.object.EmployeeDO;
import com.alifi.crm.dal.object.WinRecordDO;

/**
 * 
 * 
 * @author wb_liangzhou.yan
 * @version $Id: LotteryAction.java, v 0.1 2013-4-24 下午07:03:40 wb_liangzhou.yan Exp $
 */
public class LotteryAction {
    
    @Resource(name = "lotteryManager")
    private LotteryManager lotteryManager;
    
    protected static final Logger      logger = LoggerFactory.getLogger(LotteryAction.class);
    
    protected static final Logger      logPermission = LoggerFactory.getLogger("uums-permission-logger");
    
    
    /**
     * @param request
     * @param response
     * @param ctx
     */
    public void doLottery(HttpServletRequest request, HttpServletResponse response,Navigator nav,final Context ctx){
        String status = "";
        String total = "0%"; 
        try {
            ctx.put("action", "true");   //标记进入过action
            SimpleSSOUser user = SimpleUserUtil.findUser(request);
            if((user==null)||StringUtil.isBlank(user.getEmpId())){      //检查
                status = LotteryResult.不准入.code();
                return;
            }
                       
            ctx.put("user", user);
            

            String currentDateStr = new SimpleDateFormat("yyyyMMdd").format(new Date());
            Long currentDataLong = Long.parseLong(currentDateStr);
            currentDataLong = 20130529L;// 暂时取消时间限制
            if (currentDataLong < 20130529) {
            	status = LotteryResult.活动没开始.code(); 
            } else if (currentDataLong > 20130530) {
            	status = LotteryResult.活动已经结束.code();
            } else {
	            //抽奖具体实现
	            LotteryResult result = lotteryManager.lottery(user.getEmpId(),user.getNickNameCn(), user.getLastName());
	            status = result.code();
            }
            
            //获取个人中奖纪录
            List<WinRecordDO> winRecords = lotteryManager.selectByEmployeeNum(user.getEmpId());
            if(CollectionUtils.isNotEmpty(winRecords)){
                int perTotal = 0;
                for (WinRecordDO winRecord : winRecords) {
                    if(StringUtil.isNotBlank(winRecord.getPrizeType())){
                        perTotal += Integer.valueOf(winRecord.getPrizeType());
                    }
                }
                total = String.valueOf(perTotal)+ "%";
            }
        } catch (Exception e) {
            ctx.put("error", new GuessMessage("exception",e.getMessage(),""));
            logger.error(e);
        } finally{
            JSONObject json = new JSONObject();
            json.put("status", status);
            json.put("total", total);
            try {
                response.getWriter().println(json.toString());
            } catch (IOException e) {
                logger.error("IOException", e);
            }
        }
    }
    
    
    /**
     * @param request
     * @param response
     * @param ctx
     */
    public void doGetTimes(HttpServletRequest request, HttpServletResponse response,Navigator nav,final Context ctx){
        int times = 0;
        try {
            ctx.put("action", "true");   //标记进入过action
            SimpleSSOUser user = SimpleUserUtil.findUser(request);
            if((user==null)||StringUtil.isBlank(user.getEmpId())){      //检查
                return;
            }
            ctx.put("user", user);
           
            EmployeeDO employee = lotteryManager.getEmployeeInfo(user.getEmpId());
            if(employee != null){
                times = employee.getAvailLotteryTime().intValue();
            }
            
        } catch (Exception e) {
            logger.error(e);
        } finally{
            JSONObject json = new JSONObject();
            json.put("times", times);
            try {
                response.getWriter().println(json.toString());
            } catch (IOException e) {
                logger.error("IOException", e);
            }
        }
    }
    
}
